package com.ls.fw.mvc.springmvc.support.jsonp.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.ls.fw.mvc.springmvc.support.jsonp.handler.JsonCallbackCheck;
import com.ls.fw.mvc.springmvc.support.view.json.JsonView;
import com.ls.fw.mvc.springmvc.util.ViewUtil;
import com.ls.fw.web.core.annotation.EnableJsonp;

/**
 * jsonp拦截器
 * @author lisheng
 * @date 2015年12月16日 下午8:14:54
 * @version V1.0
 */
public class JsonpInterceptor implements HandlerInterceptor {
	
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	protected JsonCallbackCheck jsonCallbackCheck;
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		 boolean ret = true; 
		 return ret;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView mav) throws Exception {
		 if (handler instanceof HandlerMethod) {
			 HandlerMethod handlerMethod = (HandlerMethod) handler;
			 EnableJsonp enableJsonp = handlerMethod.getMethodAnnotation(EnableJsonp.class);
			 if(enableJsonp != null && mav.getViewName()==null){
				 response.setContentType(JsonView.DEFAULT_JSONP_CONTENT_TYPE);
				 ViewUtil.convert(mav, request, true, true, jsonCallbackCheck);
			 }
		 } 
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
	 
	public JsonCallbackCheck getJsonCallbackCheck() {
		return this.jsonCallbackCheck;
	}

	public void setJsonCallbackCheck(JsonCallbackCheck jsonCallbackCheck) {
		this.jsonCallbackCheck = jsonCallbackCheck;
	}
}
